//
//  TopBar.swift
//  SwiftDemo
//
//  Created by zhudeshuai on 2018/9/14.
//  Copyright © 2018年 zhudeshuai. All rights reserved.
//

import Foundation
import UIKit
/*
    自定义页面头部
 
 */
class TopBar:UIView {
    var backBtn:UIButton!
    var titleLabel:UILabel!
    var isFirstLayout:Bool = true
    
    typealias SwiftBlock = () -> Void
    
    var backBlock: SwiftBlock?
    
    override init(frame:CGRect) {
        super.init(frame:frame)
        initView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initView()
    }
    
    func initView() {
        self.backgroundColor = UIColor.blue
        //1.添加返回按钮
        backBtn = UIButton()
        backBtn.backgroundColor = UIColor.red
        backBtn.setTitle("返回", for: UIControlState.normal)
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10)
        backBtn.addTarget(self, action: #selector(addBackAction), for: .touchUpInside)
        self.addSubview(backBtn)
        //2.添加标题
        titleLabel = UILabel()
        titleLabel.text = "我是标题"
        titleLabel.textColor = UIColor.white
        self.addSubview(titleLabel)
        
    }
    //添加返回按钮响应
    func setBackBlock(block: @escaping SwiftBlock) {
        backBlock = block;
    }
    
    //设置标题
    func setTitle(title:String) {
        titleLabel.text = title
    }
    
    
    @objc func addBackAction() {
        if (backBlock != nil) {
            backBlock!()
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if (isFirstLayout) {
            //返回按钮
            backBtn.snp.makeConstraints{(make) in
                make.height.left.top.equalToSuperview()
            }
            backBtn.sizeToFit()
            
            //标题
            titleLabel.snp.makeConstraints{(make) in
                make.top.centerX.height.equalToSuperview()
            }
            titleLabel.sizeToFit()
            
            isFirstLayout = false
        }
        
        
    }
}
